package com.scpii.api.common.auth.token;

import java.io.IOException;
import java.util.Date;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;

import com.scpii.api.domain.auth.UsersInfoDetails;

public class AuthAccessTokenSerializer extends JsonSerializer<AuthAccessToken> {

	@Override
	public void serialize(AuthAccessToken value, JsonGenerator jgen,
			SerializerProvider provider) throws IOException,
			JsonProcessingException {
		jgen.writeStartObject();
		jgen.writeStringField(AuthAccessToken.ACCESS_TOKEN, value.getValue());
		AuthRefreshToken refreshToken = value.getRefreshToken();
		if (refreshToken != null) {
			jgen.writeStringField(AuthAccessToken.REFRESH_TOKEN,
					refreshToken.getValue());
		}
		Date expiration = value.getExpiration();
		if (expiration != null) {
			long now = System.currentTimeMillis();
			jgen.writeNumberField(AuthAccessToken.EXPIRES_IN,
					(expiration.getTime() - now) / 1000);
		}
		UsersInfoDetails user = value.getUsersInfoDetails();
		if (user != null) {
			jgen.writeObjectField(AuthAccessToken.USER, user);
		}
		jgen.writeEndObject();
	}
}
